/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import model.Base;
import view.LoginView;

/**
 *
 * @author Ira
 */
public class LoginControler implements ActionListener, KeyListener {

	private Base model;
	private LoginView view;
	
	public LoginControler(Base model, LoginView view) {
		this.model = model;
		this.view = view;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(((JComponent)e.getSource()).getName().equals(LoginView.BTN_QUIT)) {
			this.quit();
		}
		else if(((JComponent)e.getSource()).getName().equals(LoginView.BTN_LOG)) {
			this.login();
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {
		
	}

	@Override
	public void keyPressed(KeyEvent e) {
		if(e.getKeyCode() == KeyEvent.VK_ENTER) {
			if(((JComponent)e.getSource()).getName().equals(LoginView.BTN_QUIT)) {
				this.quit();
			}
			else {
				this.login();
			}
		}
		else if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
			this.quit();
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
	
	}
	
	private void quit() {
		this.model.serialize();
		System.exit(0);
	}
	
	private void login() {
		int result = this.model.login(this.view.getPseudo(), this.view.getPass());
		if(result == 0) {
			this.view.setInfo("<html><center>Connection impossible, vérifiez vos" +
					"<br/>identifiants</center></html>");
		}
		else {
			this.view.accessContent(result);
		}			
	}
}
